import { CCObject, _decorator } from 'cc';
import { PageBase } from './PageBase';
const { ccclass, property } = _decorator;

@ccclass('PageController')
export class PageController extends CCObject {

    private _currentIdx: number = -1;
    private _pages: { [idx: number]: PageBase; } = {};

    public addPage(idx: number, page: PageBase): boolean {
        let a = this._pages[idx];
        if (a) {
            console.error(`不能重复设定页面 id:${idx}`);
            return false;
        } else {
            page.pageIdx = idx;
            this._pages[idx] = page;
            return true;
        }
    }

    public showPage(idx: number, params?: any,
        onEffect?: (oldPage: PageBase, newPage: PageBase, onComplete: () => void, cbThis: any) => void,
        cbThis?: any): void {
        //
        let page: PageBase = this._pages[idx];
        if (page) {
            page.showPage(params);
            //
            if (idx >= 0 && this._currentIdx != idx) {
                let prePage: PageBase = this._pages[this._currentIdx];
                if (prePage) {
                    if (onEffect) {
                        onEffect.call(cbThis, prePage, page, () => {
                            prePage.hidePage();
                        }, this);
                    } else {
                        prePage.hidePage();
                    }
                } else {
                    onEffect.call(cbThis, null, page, () => {
                        // do nothing
                    }, this);
                }
                this._currentIdx = idx;
            }
        } else {
            console.error(`没有设定此页面`);
        }
    }


    public get currentIdx(): number {
        return this._currentIdx;
    }

    public get currentPage(): PageBase {
        if (this._currentIdx >= 0) {
            return this._pages[this._currentIdx];
        } else {
            return null;
        }
    }

}


